package com.example.yangyinzhaixian.uitl;

import android.app.Application;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import java.util.List;

/**
 * 全局应用
 *
 * @作者 lc
 *
 * @公司:com.beicai
 *
 * @时间 2015-11-3
 */
public class MyBaseApplication extends Application {
	private static MyBaseApplication mInstance; // 实例
	private HttpClient httpClient; // 主要用于图片缓存 获取图片流对象
	public static int GOODS_INDEX = 0;
	public static List<String> DETAIL_IMAGEURL = null;
	public static String UNAME = null;


	/**
	 * @Description:获得实例
	 * @return
	 */
	public static MyBaseApplication getInstance() {
		return mInstance;
	}


	/**
	 * list单例模式
	 *
	 * @return
	 */

	/**
	 * 程序创建
	 */
	@Override
	public void onCreate() {
		super.onCreate();
		mInstance = this;
		httpClient = this.createHttpClient(); // 保证程序运行的时候即时创建一个

	}

	/**
	 * 内存不足时关闭连接
	 */
	@Override
	public void onLowMemory() {
		super.onLowMemory();
		this.shutdownHttpClient();
	}

	/**
	 * 不正常结束时 关闭连接
	 */
	@Override
	public void onTerminate() {
		super.onTerminate();
		this.shutdownHttpClient();
	}

	/**
	 * @Description: 创建一个HttpClient实例
	 * @return
	 */
	private HttpClient createHttpClient() {
		HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params,
				HTTP.DEFAULT_CONTENT_CHARSET);
		HttpProtocolParams.setUseExpectContinue(params, true);
		HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
		HttpConnectionParams.setSoTimeout(params, 20 * 1000);
		HttpConnectionParams.setSocketBufferSize(params, 8192);
		SchemeRegistry schReg = new SchemeRegistry();
		schReg.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		schReg.register(new Scheme("https",
				SSLSocketFactory.getSocketFactory(), 443));

		ClientConnectionManager connMgr = new ThreadSafeClientConnManager(
				params, schReg);

		return new DefaultHttpClient(connMgr, params);
	}

	/**
	 *
	 * @Description:关闭连接管理器并释放资源
	 */
	public void shutdownHttpClient() {
		if (httpClient != null && httpClient.getConnectionManager() != null) {
			httpClient.getConnectionManager().shutdown();
		}
	}

	/**
	 *
	 * @Description:对外提供HttpClient实例
	 * @return
	 */
	public HttpClient getHttpClient() {
		return httpClient;
	}
}
